package ru.ipo.problemsapi;

import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: ilya
 * Date: 28.03.11
 * Time: 19:46
 */
public class ExtendedProblem implements Problem {

    private final Problem problem;

    public ExtendedProblem(Problem problem) {
        this.problem = problem;
    }

    public Problem getProblem() {
        return problem;
    }

    public String getResourceType(String path) {
        return problem.getString(path + "~type");
    }

    public String getName() {
        return problem.getString("name");
    }

    public String getClientPlugin() {
        return problem.getString("client plugin");
    }

    public String getServerPlugin() {
        return problem.getString("server plugin");
    }

    public InputStream getStatement() {
        return problem.getReadStream("statement");
    }

    public String getDebugStatement() {
        return problem.getString("debug statement");
    }

    public String getStatementType() {
        return getResourceType("statement");
    }

    public String getAnswer() {
        return getString("answer");
    }

    //delegate methods

    public InputStream getReadStream(String name) {
        return problem.getReadStream(name);
    }

    public String getString(String name) {
        return problem.getString(name);
    }

    public boolean isTeacher(String name) {
        return problem.isTeacher(name);
    }

    public List<String> listNames() {
        return problem.listNames();
    }

    //TODO get class MimeType from Java2EE (low priority)
    public Charset getEncoding(String res) {
        String resType;
        if (res.endsWith("~type"))
            return Charset.forName("UTF-8");
        else
            resType = getString(res + "~type");

        if (resType == null)
            return Charset.forName("UTF-8");

        if (resType.indexOf(";") == -1)
            return Charset.forName("UTF-8");

        if (resType.toLowerCase().lastIndexOf("charset") == -1)
            return Charset.forName("UTF-8");

        resType = resType.substring(resType.toLowerCase().indexOf("charset") + "charset".length());

        if (resType.indexOf("=") == -1)
            return Charset.forName("UTF-8");

        resType = resType.substring(resType.indexOf("=") + 1);

        if (resType.indexOf(";") != -1)
            resType = resType.substring(0, resType.indexOf(";"));

        return Charset.forName(resType.trim());
    }
}
